/**
 * @ClassName: UserInvoiceService
 * @Description:鍙戠エ琛�
 * @author 832
 * @date 2016-12-08
 */
package com.fzrskj.cloud.free.user.service;

import com.fzrskj.cloud.free.consts.AppCode;
import com.fzrskj.cloud.free.consts.CConsts;
import com.fzrskj.cloud.free.core.tool.CDateTimeTool;
import com.fzrskj.cloud.free.core.tool.CJsonTool;
import com.fzrskj.cloud.free.core.tool.CSessionTool;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.ConfigPropUtils;
import com.fzrskj.cloud.free.core.utils.EncryptUtils;
import com.fzrskj.cloud.free.core.utils.JxlExpExcelUtils;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.user.bean.UserInvoiceView;
import com.fzrskj.cloud.free.user.bean.UserInvoice;
import com.fzrskj.cloud.free.user.utils.UserInvoiceUtil;
import com.winiis.component.common.utils.encrypt.Encrypt3DESUtils;
import com.winiis.component.common.utils.tool.CSysTool;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.tool.StrTool;
import ms.core.tool.XmlCodeParser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserInvoiceService extends CObject {
	
	/**
	 * 新增发票记录
	 * 
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String addUserInvoice(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		int uid = CloudContextUtils.getSession().getUID();
		String userName = CSessionTool.getAccountCloud(sid);
		double amount = Double.parseDouble(CJsonTool.getStrValue(p, "amount",""));
		String value = CJsonTool.getStrValue(p, "getType", "");
		String paramEName = CJsonTool.getStrValue(p, "getParamEName", "");	
		
		if(amount <=0){
			return XmlCodeParser.formatCustomTips(false, "可开票金额不足");
		}
		UserInvoice userInvoice = (UserInvoice) CJsonTool.jsonToBean(p,UserInvoice.class);
		if (userInvoice == null) {
			return XmlCodeParser.formatResultTips(false,SysErr.SYS_PARAM_ERR);
		}
		userInvoice.setUserId(uid);
		userInvoice.setUserName(userName);
		userInvoice.setCreateTime(new Date());
		if(userInvoice.getPrice()<=0){
			return XmlCodeParser.formatCustomTips(false, "发票金额要大于0");
		}
		UserInvoiceUtil userInvoiceUtil = new UserInvoiceUtil();
		if(userInvoice.getPrice()>amount){
			return XmlCodeParser.formatCustomTips(false, "发票金额不能大于总消费金额");
		}

		String openAccount = userInvoice.getOpenAccount();
		if (!StrTool.isBlankStr(openAccount)) {
			openAccount = EncryptUtils.decodeSession(openAccount);
			userInvoice.setOpenAccount(Encrypt3DESUtils.encrypt(openAccount, ConfigPropUtils.getEncryptKeyService()));
		}

		String contactNumber = userInvoice.getContactNumber();
		if (!StrTool.isBlankStr(contactNumber)) {
			contactNumber = EncryptUtils.decodeSession(contactNumber);
			userInvoice.setContactNumber(Encrypt3DESUtils.encrypt(contactNumber, ConfigPropUtils.getEncryptKeyService()));
		}

		String telephone = userInvoice.getTelephone();
		if (!StrTool.isBlankStr(telephone)) {
			telephone = EncryptUtils.decodeSession(telephone);
			userInvoice.setTelephone(Encrypt3DESUtils.encrypt(telephone, ConfigPropUtils.getEncryptKeyService()));
		}
		
		int retCode = userInvoiceUtil.addUserInvoice(userInvoice,paramEName, value);
		String code = userInvoiceUtil.getErrCode();	
		if(retCode<0){
			return XmlCodeParser.formatCustomTips(false, code);
		}
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultTips(true, code);
		
	}
	
	/**
	 * 查询全部发票
	 * 
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String getAllInvoice(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		int uid = CloudContextUtils.getSession().getUID();
		int uType=CSessionTool.getAccountTypeCloud(sid);
		
		String type = CJsonTool.getStrValue(p, "type", "");
		String header = CJsonTool.getStrValue(p, "header", "");
		String content = CJsonTool.getStrValue(p, "content", "");
		String start = CJsonTool.getStrValue(p, "start", "");
		String end = CJsonTool.getStrValue(p, "end", "");
		int page = CJsonTool.getIntValue(p, "page", 1);
		int pageSize = CJsonTool.getIntValue(p, "pagesize", CConsts.PAGE_SIZE);
		
		Map<String, Object> cdt = new HashMap<String, Object>();
		if (!CStrTool.isBlankStr(type)) {cdt.put("type", type);}
		if (!CStrTool.isBlankStr(header)) {cdt.put("header", header);}
		if (!CStrTool.isBlankStr(content)) {cdt.put("content", content);}
		if (!CStrTool.isBlankStr(start)) {
			Date starts = CDateTimeTool.strToDate(start);
			cdt.put("start", starts);
		}
		if (!CStrTool.isBlankStr(end)) {
			Date ends = CDateTimeTool.strToDate(end);
			cdt.put("end", CDateTimeTool.incDay(ends, 1));
		}
		if(uType>0) {
			cdt.put("userId", uid);
		}

		UserInvoiceUtil uiUtils = new UserInvoiceUtil();
		// 查询总记录数
		int count = uiUtils.getUserInvoiceCount(cdt);
		String code = uiUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		int pages = Math.round((count + pageSize - 1) / pageSize);

		// 查询记录
		List<UserInvoiceView> list = uiUtils.getAllInvoice(cdt,page, pageSize);
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		return XmlCodeParser.formatResultPageData(code, page, pages, pageSize,count, CJsonTool.listBeanToJson(list));
	}

	/**
	 * 删除发票记录
	 * 
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String delinvoice(HttpServletRequest req, HttpServletResponse resp,
                             String p, String sid) {
		String userName = CJsonTool.getStrValue(p, "userName", "");
		if (StrTool.isBlankStr(userName)) {
			userName = CSessionTool.getAccountCloud(sid);
		}

		int id = CJsonTool.getIntValue(p, "id", -1);
		if (id <= 0) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		UserInvoiceUtil userInvoiceUtil = new UserInvoiceUtil();
		userInvoiceUtil.delinvoice(userName, id);
		String code = userInvoiceUtil.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultTips(true, code);
	}

	/**
	 * 更新发票信息
	 * 
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String uptInvoice(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		int uid = CloudContextUtils.getSession().getUID();
		
		UserInvoice userInvoice = (UserInvoice)CJsonTool.jsonToBean(p,UserInvoice.class);
		if (userInvoice == null) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		
		UserInvoiceUtil uiUtil = new UserInvoiceUtil();
		UserInvoice ui=uiUtil.queryUIById(userInvoice.getId());
		if(ui==null) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_EXISTS);
		}
		if (ui.getStatus().equals("Y")) {
			return XmlCodeParser.formatResultTips(false, AppCode.INVOICE_NO_UPDATA);
		}
		userInvoice.setUserId(uid);
		userInvoice.setStatus("N");

		String openAccount = userInvoice.getOpenAccount();
		if (!StrTool.isBlankStr(openAccount)) {
			openAccount = EncryptUtils.decodeSession(openAccount);
			userInvoice.setOpenAccount(Encrypt3DESUtils.encrypt(openAccount, ConfigPropUtils.getEncryptKeyService()));
		}

		String contactNumber = userInvoice.getContactNumber();
		if (!StrTool.isBlankStr(contactNumber)) {
			contactNumber = EncryptUtils.decodeSession(contactNumber);
			userInvoice.setContactNumber(Encrypt3DESUtils.encrypt(contactNumber, ConfigPropUtils.getEncryptKeyService()));
		}

		String telephone = userInvoice.getTelephone();
		if (!StrTool.isBlankStr(telephone)) {
			telephone = EncryptUtils.decodeSession(telephone);
			userInvoice.setTelephone(Encrypt3DESUtils.encrypt(telephone, ConfigPropUtils.getEncryptKeyService()));
		}

		int ret=uiUtil.uptInvoice(userInvoice);
		String code = uiUtil.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultTips(ret>0, code);
	}

	/**
	 * 发票审核
	 * 
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String invoiceAudit(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		String userName=CSessionTool.getAccountCloud(sid);
		String status = CJsonTool.getStrValue(p, "status", "");
		String courierNumber = CJsonTool.getStrValue(p, "courierNumber", "");
		String auditingResult = CJsonTool.getStrValue(p, "auditingResult", "");
		String attachment = CJsonTool.getStrValue(p, "attachment", "");
		int id = CJsonTool.getIntValue(p, "id", -1);
		if (id <= 0) {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
		
		Map<String,Object> values = new HashMap<String, Object>();
		values.put("status", status);
		values.put("courierNumber", courierNumber);
		values.put("auditingResult", auditingResult);
		values.put("auditTime", new Date());
		values.put("auditor", userName);
		values.put("attachment", attachment);
		Map<String,Object> cdt = new HashMap<String, Object>();
		cdt.put("id", id);
		
		UserInvoiceUtil uiUtil = new UserInvoiceUtil();
		uiUtil.invoiceAudit(values,cdt);
		String code = uiUtil.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultTips(true, code);
	}

	/**
	 * 查询历史发票
	 * 
	 * @param req
	 * @param resp
	 * @param sid
	 * @return
	 */
	public String queryHistory(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		String userName = CSessionTool.getAccountCloud(sid);
		UserInvoiceUtil userInvoiceutil = new UserInvoiceUtil();
		List<UserInvoice> queryName = userInvoiceutil.queryHistory(userName);
		String code = userInvoiceutil.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}
		return XmlCodeParser.formatResultData(true, code, CJsonTool.listBeanToJson(queryName));
	}

	/**
	 * 查询发票详情
	 * 
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String queryUserInvoice(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		int uid = CloudContextUtils.getSession().getUID();
		int uType=CSessionTool.getAccountTypeCloud(sid);
		if(uType==0) {
			uid = 0;
		}
		
		int id = CJsonTool.getIntValue(p, "id", 0);
		UserInvoiceUtil uiUtils = new UserInvoiceUtil();
		UserInvoiceView ret = uiUtils.queryUserInvoice(id, uid);
		String code = uiUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)) {
			return XmlCodeParser.formatResultTips(false, code);
		}

		String openAccount = ret.getOpenAccount();
		if (!StrTool.isBlankStr(openAccount)) {
			openAccount = Encrypt3DESUtils.decrypt(openAccount, ConfigPropUtils.getEncryptKeyService());
			ret.setOpenAccount(EncryptUtils.encodeSession(openAccount));
		}

		String contactNumber = ret.getContactNumber();
		if (!StrTool.isBlankStr(contactNumber)) {
			contactNumber = Encrypt3DESUtils.decrypt(contactNumber, ConfigPropUtils.getEncryptKeyService());
			ret.setContactNumber(EncryptUtils.encodeSession(contactNumber));
		}

		String telephone = ret.getTelephone();
		if (!StrTool.isBlankStr(telephone)) {
			telephone = Encrypt3DESUtils.decrypt(telephone, ConfigPropUtils.getEncryptKeyService());
			ret.setTelephone(EncryptUtils.encodeSession(telephone));
		}

		return XmlCodeParser.formatResultData(true, code,CJsonTool.beanToJson(ret));
	}

	/**
	 * 导出excel
	 * 
	 * @param req
	 * @param resp
	 * @param p
	 * @param sid
	 * @return
	 */
	public String exportExcel(HttpServletRequest req, HttpServletResponse resp, String p, String sid) {
		String id = CJsonTool.getStrValue(p, "id", "");
		if (id.equals("")) {
			return XmlCodeParser.formatResultTips(false,AppCode.INVOICE_NOT_EXISTS);
		}
		String[] array = id.split(",");
		JxlExpExcelUtils jxlExpExcel = new JxlExpExcelUtils();
		String excelPath = req.getSession().getServletContext()
				.getRealPath("/excel");
		CSysTool.dirExists(excelPath, true);
		String code = jxlExpExcel.exportExcel(array, excelPath);
		String FileName ="\"" + DicParamUtils.getParamValue("weburl")+"/excel/"+CJsonTool.getStrValue(code, "FileName", "-1") + "\"";
		if (CJsonTool.getStrValue(code, "code", "-1").equals("1")) {
			return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, FileName);
		} else {
			return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
		}
	}
}
